package tool;
import java.util.Base64;
public class Decryption {
        public String Decode(String text) {
            String railFenceDecoded = railFenceDecrypt(text, 2);
            return base64Decode(railFenceDecoded);
        }

        private static String base64Decode(String input) {
            byte[] decodedBytes = Base64.getDecoder().decode(input);
            return new String(decodedBytes);
        }

        private static String railFenceDecrypt(String text, int rails) {
            int n = text.length();
            char[] result = new char[n];
            int[] railLengths = new int[rails];
            boolean dirDown = false;
            int row = 0;
            for (int i = 0; i < n; i++) {
                railLengths[row]++;
                if (row == 0 || row == rails - 1) {
                    dirDown = !dirDown;
                }
                row += dirDown ? 1 : -1;
            }
            int index = 0;
            for (int r = 0; r < rails; r++) {
                for (int i = 0; i < railLengths[r]; i++) {
                    result[index++] = text.charAt(i);
                }
            }
            StringBuilder decodedText = new StringBuilder();
            row = 0;
            dirDown = false;
            for (int i = 0; i < n; i++) {
                decodedText.append(result[row]);
                if (row == 0 || row == rails - 1) {
                    dirDown = !dirDown;
                }
                row += dirDown ? 1 : -1;
            }

            return decodedText.toString();
        }
    }
